﻿using System;
using System.Linq.Expressions;

namespace GDM.Hogar.Soporte
{
    public static class FlexReflector
    {
        public static string GetPropertyName<T>(Expression<Func<T>> expression)
        {
            if (expression.Body.NodeType == ExpressionType.MemberAccess)
            {
                var memberExpression = expression.Body as MemberExpression;
                if (memberExpression != null)
                    return memberExpression.Member.Name;
            }
            throw new NotSupportedException("This overload accepts only member access lambda expressions");
        }

        public static string GetPropertyName<TItem, TResult>(Expression<Func<TItem, TResult>> expression)
        {
            if (expression.Body.NodeType == ExpressionType.MemberAccess)
            {
                return ((MemberExpression)expression.Body).Member.Name;
            }
            if (expression.Body.NodeType == ExpressionType.Convert)
            {
                var op = ((UnaryExpression)expression.Body).Operand;
                return ((MemberExpression)op).Member.Name;
            }
            throw new NotSupportedException("This overload accepts only member access lambda expressions");
        }
    }

    public static class FlexReflectorExtensions
    {
        public static string GetPropertyName<T>(this T instance, Expression<Func<T, object>> propertyAccesor)
        {
            return FlexReflector.GetPropertyName(propertyAccesor);
        }
    }
}